$(function () {
  function bindCaptchaClick() {
    $("#captcha-btn").click(function () {
      let $this = $(this);
      let email = $("input[name='email']").val();
      if (!email) {
        alert("请先输入邮箱！");
        return;
      }
      // 取消按钮点击事件
      $this.off("click");
      // 发送ajax请求
      $.ajax("/myauth/captcha?email=" + email, {
        method: "GET",
        success: function (res) {
          if (res["code"] == 200) {
            alert("验证码发送成功！");
          } else {
            alert(res["message"]);
          }
        },
        fail: function (err) {
          console.log(err);
        },
      });
      // 倒计时
      let countdown = 6;
      let timer = setInterval(() => {
        if (countdown <= 0) {
          $this.text("获取验证码");
          clearInterval(timer);
          // 重新绑定点击事件
          bindCaptchaClick();
        } else {
          countdown--;
          $this.text(countdown + "s");
        }
      }, 1000);
    });
  }

  bindCaptchaClick();
});
